import React, { createContext, useState, useContext } from 'react';

// 创建标签页管理上下文
export const TabsContext = createContext();

// TabsContext提供者组件
export const TabsProvider = ({ children }) => {
  // 标签页列表
  const [tabs, setTabs] = useState([
    { key: 'home', title: '首页', closable: false }
  ]);
  
  // 当前活动标签页
  const [activeTab, setActiveTab] = useState('home');
  
  // 标签内容映射
  const [tabContents, setTabContents] = useState({});

  // 添加标签页
  const addTab = (key, title, componentType, props = {}) => {
    // 检查标签是否已经存在
    if (!tabs.find(tab => tab.key === key)) {
      setTabs(prev => [...prev, { key, title, closable: true }]);
      
      // 保存标签的组件类型和属性
      setTabContents(prev => ({
        ...prev,
        [key]: { componentType, props }
      }));
    }
    setActiveTab(key);
  };

  // 切换标签页
  const changeTab = (key) => {
    setActiveTab(key);
  };

  // 关闭标签页
  const closeTab = (targetKey) => {
    const newTabs = tabs.filter(tab => tab.key !== targetKey);
    setTabs(newTabs);
    
    // 如果关闭的是当前标签，则切换到其他标签
    if (targetKey === activeTab) {
      setActiveTab(newTabs[newTabs.length - 1]?.key || 'home');
    }
    
    // 清除标签内容
    setTabContents(prev => {
      const newContents = { ...prev };
      delete newContents[targetKey];
      return newContents;
    });
  };

  return (
    <TabsContext.Provider
      value={{
        tabs,
        activeTab,
        tabContents,
        addTab,
        changeTab,
        closeTab
      }}
    >
      {children}
    </TabsContext.Provider>
  );
};

// 自定义Hook方便使用TabsContext
export const useTabs = () => useContext(TabsContext); 